package com.hay.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hay.common.PageResult;
import com.hay.item.mapper.BrandMapper;
import com.hay.item.pojo.Brand;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @title: BrandService
 * @Author HuangYan
 * @Date: 2020/7/17 22:25
 * @Version 1.0
 */
@Service
public class BrandService {

    @Autowired
    private BrandMapper brandMapper;

    /**
     * 根据查询条件分页并排序查询品牌信息
     * @param key
     * @param page
     * @param rows
     * @param sortBy
     * @param desc
     * @return
     */
    public PageResult<Brand> queryBrandsByPage(String key, Integer page, Integer rows, String sortBy, Boolean desc) {

        // 初始化example对象
        Example example = new Example(Brand.class);
        Example.Criteria criteria = example.createCriteria();

        // 如果输入的关键字key不为空，则根据name模糊查询，或者根据首字母查询
        if (StringUtils.isNotBlank(key)){
            criteria.andLike("name","%" + key + "%").orEqualTo("letter",key);
        }
        // 如果排序字段sortBy不为空，则进行排序
        if (StringUtils.isNotBlank(sortBy)){
            example.setOrderByClause(sortBy +" " + (desc ? "desc" : "asc"));
        }
        PageHelper.startPage(page,rows);
        List<Brand> brands = brandMapper.selectByExample(example);
        PageInfo<Brand> pageInfo = new PageInfo<>(brands);
        return new PageResult<>(pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getList());
    }

    /**
     * 新增品牌
     * @param brand
     * @param ids
     */
    @Transactional
    public void insertBrand(Brand brand, List<Long> ids) {
        // 新增品牌
        brandMapper.insertSelective(brand);
        // 新增品牌与类别中间表
        for (long id: ids) {
            brandMapper.insertCategoryAndBrandId(id, brand.getId());
        }

    }

    /**
     * 删除商品
     * @param bid
     * @return
     */
    @Transactional
    public void deleteBrandByBid(long bid) {
        Brand brand = new Brand();
        brand.setId(bid);
        brandMapper.deleteCategoryAndBrandByBid(bid);
        brandMapper.delete(brand);
    }
    /**
     * 根据商品分类cid查询此分类下的商品
     * @param cid
     * @return
     */
    public List<Brand> queryBrandListByCid(long cid) {
        return brandMapper.queryBrandListByCid(cid);
    }

    public Brand queryBrandById(Long id) {
        return brandMapper.selectByPrimaryKey(id);
    }
}
